import React, { useState } from 'react';
import styled from 'styled-components';
import { Form, Input, Button, Tabs, Toast } from 'antd-mobile';
import { FaWeixin, FaQq } from 'react-icons/fa';
import { useNavigate } from 'react-router-dom';
import { motion } from 'framer-motion';

const theme = {
  primary: '#6366F1',
  secondary: '#818CF8',
  background: '#F7F7F7',
  text: '#2D3436',
  lightText: '#64748B',
};

interface PhoneFormValues {
  phone: string;
  code: string;
}

interface AccountFormValues {
  phone: string;
  password: string;
  confirmPassword: string;
}

const Register: React.FC = () => {
  const [activeTab, setActiveTab] = useState('phone');
  const [countdown, setCountdown] = useState(0);
  const navigate = useNavigate();
  const [phoneForm] = Form.useForm<PhoneFormValues>();
  const [accountForm] = Form.useForm<AccountFormValues>();

  const startCountdown = () => {
    setCountdown(60);
    const timer = setInterval(() => {
      setCountdown((prev) => {
        if (prev <= 1) {
          clearInterval(timer);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
  };

  const handleSendCode = async () => {
    try {
      await phoneForm.validateFields(['phone']);
      const phone = phoneForm.getFieldValue('phone');
      // TODO: 发送验证码到手机
      Toast.show({
        icon: 'success',
        content: '验证码已发送',
      });
      startCountdown();
    } catch (error) {
      Toast.show({
        icon: 'error',
        content: '请输入正确的手机号',
      });
    }
  };

  const handlePhoneRegister = async () => {
    try {
      const values = await phoneForm.validateFields();
      console.log('手机注册:', values);
      // TODO: 处理手机注册逻辑
      Toast.show({
        icon: 'success',
        content: '注册成功',
      });
      navigate('/login');
    } catch (error) {
      Toast.show({
        icon: 'error',
        content: '请检查表单信息',
      });
    }
  };

  const handleAccountRegister = async () => {
    try {
      const values = await accountForm.validateFields();
      console.log('账号注册:', values);
      // TODO: 处理账号注册逻辑
      Toast.show({
        icon: 'success',
        content: '注册成功',
      });
      navigate('/login');
    } catch (error) {
      Toast.show({
        icon: 'error',
        content: '请检查表单信息',
      });
    }
  };

  const handleSocialLogin = (type: 'wechat' | 'qq') => {
    Toast.show({
      icon: 'loading',
      content: `正在使用${type === 'wechat' ? '微信' : 'QQ'}登录...`,
    });
    // TODO: 实现社交账号登录逻辑
  };

  return (
    <PageContainer>
      <ContentWrapper
        as={motion.div}
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
      >
        <Header>注册账号</Header>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <Tabs.Tab title="手机验证码注册" key="phone">
            <Form
              form={phoneForm}
              layout="vertical"
              footer={
                <StyledButton block onClick={handlePhoneRegister}>
                  注册
                </StyledButton>
              }
            >
              <Form.Item
                label="手机号"
                name="phone"
                rules={[
                  { required: true, message: '请输入手机号' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
                ]}
              >
                <StyledInput placeholder="请输入手机号" />
              </Form.Item>
              <Form.Item
                label="验证码"
                name="code"
                rules={[{ required: true, message: '请输入验证码' }]}
                extra={
                  <CodeButton
                    disabled={countdown > 0}
                    onClick={handleSendCode}
                  >
                    {countdown > 0 ? `${countdown}秒后重试` : '获取验证码'}
                  </CodeButton>
                }
              >
                <StyledInput placeholder="请输入验证码" />
              </Form.Item>
            </Form>
          </Tabs.Tab>
          <Tabs.Tab title="账号密码注册" key="account">
            <Form
              form={accountForm}
              layout="vertical"
              footer={
                <StyledButton block onClick={handleAccountRegister}>
                  注册
                </StyledButton>
              }
            >
              <Form.Item
                label="手机号"
                name="phone"
                rules={[
                  { required: true, message: '请输入手机号' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
                ]}
              >
                <StyledInput placeholder="请输入手机号" />
              </Form.Item>
              <Form.Item
                label="密码"
                name="password"
                rules={[
                  { required: true, message: '请输入密码' },
                  { min: 6, message: '密码至少6位' },
                ]}
              >
                <StyledInput type="password" placeholder="请输入密码" />
              </Form.Item>
              <Form.Item
                label="确认密码"
                name="confirmPassword"
                rules={[
                  { required: true, message: '请确认密码' },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('password') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('两次输入的密码不一致'));
                    },
                  }),
                ]}
              >
                <StyledInput type="password" placeholder="请再次输入密码" />
              </Form.Item>
            </Form>
          </Tabs.Tab>
        </Tabs>

        <Divider>
          <DividerText>其他注册方式</DividerText>
        </Divider>

        <SocialButtons>
          <SocialButton onClick={() => handleSocialLogin('wechat')}>
            <FaWeixin /> 微信登录
          </SocialButton>
          <SocialButton onClick={() => handleSocialLogin('qq')}>
            <FaQq /> QQ登录
          </SocialButton>
        </SocialButtons>

        <LoginLink onClick={() => navigate('/login')}>
          已有账号？立即登录
        </LoginLink>
      </ContentWrapper>
    </PageContainer>
  );
};

export default Register;

const PageContainer = styled.div`
  min-height: 100vh;
  background-color: ${theme.background};
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
`;

const ContentWrapper = styled.div`
  background: white;
  border-radius: 16px;
  padding: 24px;
  width: 100%;
  max-width: 400px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
`;

const Header = styled.h1`
  text-align: center;
  color: ${theme.text};
  font-size: 24px;
  margin-bottom: 24px;
`;

const StyledInput = styled(Input)`
  &.adm-input {
    border: 1px solid #E2E8F0;
    border-radius: 8px;
    padding: 8px 12px;
    
    &:focus {
      border-color: ${theme.primary};
    }
  }
`;

const StyledButton = styled(Button)`
  &.adm-button {
    background: ${theme.primary};
    border-radius: 8px;
    color: white;
    font-size: 16px;
    height: 44px;
    
    &:hover {
      opacity: 0.9;
    }
  }
`;

const CodeButton = styled.button<{ disabled?: boolean }>`
  background: none;
  border: none;
  color: ${props => props.disabled ? theme.lightText : theme.primary};
  cursor: ${props => props.disabled ? 'not-allowed' : 'pointer'};
  padding: 4px 8px;
  font-size: 14px;
`;

const Divider = styled.div`
  display: flex;
  align-items: center;
  margin: 24px 0;
  
  &::before,
  &::after {
    content: '';
    flex: 1;
    height: 1px;
    background: #E2E8F0;
  }
`;

const DividerText = styled.span`
  color: ${theme.lightText};
  padding: 0 16px;
  font-size: 14px;
`;

const SocialButtons = styled.div`
  display: flex;
  gap: 12px;
  margin-bottom: 24px;
`;

const SocialButton = styled.button`
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  background: white;
  border: 1px solid #E2E8F0;
  border-radius: 8px;
  padding: 12px;
  color: ${theme.text};
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    border-color: ${theme.primary};
    color: ${theme.primary};
    background: rgba(99, 102, 241, 0.05);
  }
  
  svg {
    font-size: 18px;
  }
`;

const LoginLink = styled.div`
  text-align: center;
  color: ${theme.primary};
  cursor: pointer;
  font-size: 14px;
  
  &:hover {
    opacity: 0.8;
  }
`; 